<script setup>
import { CAPTCHA, PHONE } from '@/constants/regexp'


const props = defineProps({
  phone: {
    type: String,
    default: '',
  },
})
const imageCodeRef = ref(null)
const formRef = ref(null)
const form = reactive({
  phone: '',
  imageCode: '',
  imageUuid: '', // 图形验证码imageUuid
  phoneCode: '',
})
const formRules = reactive({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: PHONE,
      message: '手机号格式错误',
      trigger: ['blur'],
    },
  ],
  imageCode: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' },
    {
      pattern: CAPTCHA,
      message: '验证码格式错误',
      trigger: ['blur'],
    },
  ],
  phoneCode: [
    { required: true, message: '请输入手机验证码', trigger: 'blur' },
  ],
})

const valid = ref(false)
const isIdle = ref(true)
watch([() => form.imageCode, () => form.phone], () => {
  formRef.value?.validateField(['phone', 'imageCode'], (state) => {
    valid.value = state
  })
})
watch(props, (val) => {
  formRef.value?.resetFields()
  form.phone = val.phone
  form.imageCode = ''
  form.phoneCode = ''
})
async function sendPhoneCode() {
  const { phone, imageCode: code, imageUuid: uuid } = form
  // 判断是否是修改组件，若是则先验证手机号是否重复
  if (!props.phone) {
    // 判断充当是验证还是修改组件
    const { accountPhone } = await useRequest('VerifyRepetition', {
      accountPhone: phone,
    })
    if (accountPhone) {
      isIdle.value = true
      ElNotification({
        message: '该手机已注册',
        type: 'warning',
        duration: 2000,
      })
      return
    }
  }
  const { success } = await useRequest('GetVerificationCode', { phone, uuid, code })
  if (success) {
    ElNotification({
      message: '手机验证码发送成功',
      type: 'success',
      duration: 2000,
    })
  }
  else {
    /** 10分钟内勿重复发送 */
    isIdle.value = true
  }
}
// 3.验证手机验证码是否正确
function checkPhoneCode() {
  return new Promise((resolve, reject) => {
    formRef.value.validateField('phoneCode', async (valid) => {
      if (valid) {
        const { phone, phoneCode: code } = form
        const { valid } = await useRequest('ValidateVerificationCode', { phone, code })
        if (valid) {
          resolve({ phone, code })
          // ElNotification({
          //   message: '手机验证码填写正确',
          //   type: 'success',
          //   duration: 3000,
          // })
        }
        else {
          ElNotification({
            type: 'error',
            message: '手机验证码填写错误',
          })
          reject(new Error('手机验证码填写错误'))
        }
      }
      else {
        reject(new Error('手机验证码填写错误'))
      }
    })
  })
}

onMounted(() => {
  // 是验证身份
  if (props.phone)
    form.phone = props.phone
})

onUnmounted(() => {
  Object.assign(form, {})
})

defineExpose({
  checkPhoneCode,
  form,
})
</script>

<template>
  <!-- 身份验证 -->
  <el-form
    ref="formRef"
    :model="form"
    :rules="formRules"
    label-width="100px"
  >
    <el-form-item :label="form.phone ? '绑定手机号' : '新手机号'" prop="phone">
      <el-input
        v-model="form.phone" :disabled="!!props.phone" :clearable="!form.phone"
        placeholder="请输入新手机号"
      />
    </el-form-item>
    <el-form-item label="图形验证码" prop="imageCode">
      <div class="flex-center">
        <el-input
          v-model.trim="form.imageCode"
          class="flex-1"
          placeholder="请输入图形验证码"
        />
        <ImageCode ref="imageCodeRef" v-model="form.imageUuid" />
      </div>
    </el-form-item>

    <el-form-item label="手机验证码" prop="phoneCode">
      <div class="flex-center">
        <el-input
          v-model="form.phoneCode"
          class="flex-1"
          placeholder="请输入手机验证码"
        />
        <CountDown v-model:valid="valid" v-model:isIdle="isIdle" @click="sendPhoneCode" />
      </div>
    </el-form-item>
  </el-form>
</template>
